// 这里放的是 登录模块 请求的异步action
import { ApiResponse, LoginForm, Token } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import http from '@/utils/request'
import { setToken } from '@/utils/token'

// 登录的action  异步的action  =》 异步函数
// export const loginAction: RootThunkAction = async (dispatch) => {
//   const res = await http.post('/authorizations', values)
//   console.log(res)
//   // dispatch({type: xxx, payload: xxxx})
// }

// xxx()()()

export const loginActionCreator = (values: LoginForm) => {
  const loginAction: RootThunkAction = async (dispatch) => {
    const res = await http.post<ApiResponse<Token>>('/authorizations', values)
    // console.log(res.data.data)
    // 同步的action =》 将数据存入仓库 store =》 存本地
    dispatch({
      type: 'login/login',
      payload: res.data.data,
    } as RootAction)

    setToken(res.data.data)
  }

  return loginAction
}

// 函数专门用于创建发送验证码的异步action
export const codeActionCreator = (mobile: string): RootThunkAction => {
  return async () => {
    await http.get('/sms/codes/' + mobile)
  }
}

// export const codeActionCreator = (mobile: string): RootThunkAction => {
//   const codeAction = async () => {
//     await http.get('/sms/codes/' + mobile)
//     // console.log(res)
//     // dispatch({type: xxx, payload: xxxx})
//   }

//   return codeAction
// }
